package com.csdj.t309.interceptors;

import com.csdj.t309.contant.SessionContant;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器开始工作");
        HttpSession session = request.getSession(false);
        boolean flag = true;
        if(session == null || StringUtils.isEmpty(session.getAttribute(SessionContant.USERNAME_IN_SESSION))){
            flag = false;
        }
        if(flag){
            //执行后面的handler
            return true;
        }else{
            //用户没有登录 跳转到登录页面
            response.sendRedirect("/user/login");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
